package de.sendorian.app.forumArchive;

import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

/**
 * This Class is a simple storage for the application context and has static
 * methods to get the context for classes that are not aware of Spring
 * application context.
 * 
 * @author sendorian
 * 
 */
@Component
public class ApplicationContextHolder implements ApplicationContextAware {

    private static ApplicationContext context;


    /**
     * @return the actual Spring application context
     */
    public static ApplicationContext getApplicationContext() {
        return ApplicationContextHolder.context;
    }


    /**
     * This method is called from within the ApplicationContext once it is done
     * starting up, it will stick a reference to itself into this bean.
     * 
     * @param context
     *            a reference to the ApplicationContext.
     */
    public void setApplicationContext(ApplicationContext context) throws BeansException {
        ApplicationContextHolder.context = context;
    }


    /**
     * This is about the same as context.getBean("beanName"), except it has its
     * own static handle to the Spring context, so calling this method
     * statically will give access to the beans by name in the Spring
     * application context.
     * 
     * @param beanName
     *            the name of the bean to get.
     * @throws BeansException
     *             thrown if the defired bean could not be resolved
     * @return an Object reference to the named bean.
     */
    public static Object getBean(String beanName) throws BeansException {
        return context.getBean(beanName);
    }


    /**
     * This is about the same as context.getBean(MyType.class), except it has its
     * own static handle to the Spring context, so calling this method
     * statically will give access to the beans by name in the Spring
     * application context.
     * 
     * @param beanName
     *            the type of the bean to get.
     * @return a reference to the named bean.
     */
    public static <T> T getBean(Class<T> requiredType) throws BeansException {
        return context.getBean(requiredType);
    }
}
